package com.cloudbroker.bcs.platform.dav.middle.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.util.MD5Util;
import com.cloudbroker.bcs.common.util.ReflectionUtil;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.UserIdGetBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.request.SendWxMessageForm;
import com.cloudbroker.bcs.platform.dav.bizapi.t2service.export.WeixinT2BizService;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.dav.common.util.HttpsUtil;
import com.cloudbroker.bcs.platform.dav.middle.constants.ChannelConstant;
import com.cloudbroker.bcs.platform.dav.middle.entity.Customer;
import com.cloudbroker.bcs.platform.dav.middle.service.CustomerService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by wangxu13798 on 2016/9/19.
 */
public class RegisterAspect {
    
    @Resource
    private CustomerService customerService;
    
    @Resource
    private WeixinT2BizService weixinT2BizService;

    private static final Logger logger = LoggerFactory.getLogger(RegisterAspect.class);
    
    public Object mobileLogin(ProceedingJoinPoint pjp) throws Throwable {
        logger.info("-----进入判断是否第一次注册切面--------");
        Object[] objAry = pjp.getArgs();
        Object o = objAry[0];
        Map<String, Field> m = ReflectionUtil.listAllFields(o.getClass());
        String customer_key = ValueUtil.getString(ReflectionUtil.getValueRough(o, m.get("customer_key")));
        if (StringUtil.isBlank(customer_key)) {
            logger.info("customer_key为空");
            return pjp.proceed();
        }
        String extend_attr = ValueUtil.getString(ReflectionUtil.getValueRough(o, m.get("extend_attr")));
        String invitation_code = ValueUtil.getString(ReflectionUtil.getValueRough(o, m.get("invitation_code")));
        if(!paramCheck(extend_attr) && StringUtil.isBlank(invitation_code)){
            logger.info(extend_attr);
            logger.info("扩展字段参数错误且无邀请码");
            return pjp.proceed();
        }
        Customer c = customerService.getByKey(customer_key);
        if (c == null || !StringUtil.isBlank(c.getCustomer_name())) {
            return pjp.proceed();
        }
        Object obj = pjp.proceed();
        if (obj instanceof UserIdGetBackForm && !StringUtil.isBlank(((UserIdGetBackForm) obj).getUser_token())) {
            if (paramCheck(extend_attr)) {
                Map<String, String> jsonObject = (Map) JSON.parse(extend_attr);
                executeImpl(jsonObject.get("channel"), jsonObject.get("invite_openid"), jsonObject.get("openid"), jsonObject.get("activity_type"), jsonObject.get("activity_id"));
            }
            if (!StringUtil.isBlank(invitation_code)){
                Customer inviter = customerService.getByKey(invitation_code);
                if (inviter != null && !inviter.getCustomer_id().equals(c.getCustomer_id())){
                    customerService.updateInviterById(c.getCustomer_id(), inviter.getCustomer_id(), c.getTenant_id());
                }
            }
        }
        return obj;
    }
    
    public Object completeInfo(ProceedingJoinPoint pjp) throws Throwable {
        Object[] objAry = pjp.getArgs();
        Object o = objAry[0];
        Map<String, Field> m = ReflectionUtil.listAllFields(o.getClass());
        String customer_key = ValueUtil.getString(ReflectionUtil.getValueRough(o, m.get("customer_key")));
        if (StringUtil.isBlank(customer_key)) {
            logger.info("customer_key为空");
            return pjp.proceed();
        }
        String extend_attr = ValueUtil.getString(ReflectionUtil.getValueRough(o, m.get("extend_attr")));
        String invitation_code = ValueUtil.getString(ReflectionUtil.getValueRough(o, m.get("invitation_code")));
        if(!paramCheck(extend_attr) && StringUtil.isBlank(invitation_code)){
            logger.info(extend_attr);
            logger.info("扩展字段参数错误且邀请码为空");
            return pjp.proceed();
        }
        Customer c = customerService.getByKey(customer_key);
        if (c == null || !StringUtil.isBlank(c.getCustomer_name())) {
            return pjp.proceed();
        }
        Object obj = pjp.proceed();
        if (obj instanceof UserIdGetBackForm && !StringUtil.isBlank(((UserIdGetBackForm) obj).getUser_token())) {
            if (paramCheck(extend_attr)) {
                Map<String, String> jsonObject = (Map) JSON.parse(extend_attr);
                executeImpl(jsonObject.get("channel"), jsonObject.get("invite_openid"), jsonObject.get("openid"), jsonObject.get("activity_type"), jsonObject.get("activity_id"));
            }
            if (!StringUtil.isBlank(invitation_code)){
                Customer inviter = customerService.getByKey(invitation_code);
                if (inviter != null && !inviter.getCustomer_id().equals(c.getCustomer_id())){
                    customerService.updateInviterById(c.getCustomer_id(), inviter.getCustomer_id(), c.getTenant_id());
                }
            }
        }
        return obj;
    }

    private boolean paramCheck(String attr){
        try {
            JSONObject obj = JSON.parseObject(attr);
            if(obj == null || obj.isEmpty()){
                return false;
            }
            if(StringUtil.isBlank(obj.get("channel")+"") || StringUtil.isBlank(obj.get("invite_openid")+"")){
                return false;
            }
            if(StringUtil.isBlank(obj.get("activity_type")+"")){
                return true;
            }else if("a01".equals(obj.get("activity_type")+"")){
                if(StringUtil.isBlank(obj.get("openid")+"") || StringUtil.isBlank(obj.get("activity_id")+"")){
                    return false;
                }
                return true;
            }
        }catch (Exception e){
            return false;
        }
        return true;
    }
    
    private void sendWxMessage(String openid) {
        SendWxMessageForm sendWxMessageForm = new SendWxMessageForm();
        sendWxMessageForm.setAppid("wx136d43fa610c89a1");
        sendWxMessageForm.setSecret("a7ec9eb5e9d806e447ad4f1dcc9601fe");
        sendWxMessageForm.setOpenid(openid);
        weixinT2BizService.funcSendWxMessage(sendWxMessageForm);
    }

    private void addChestCount(String openid,String fromid,String activityId){
        String url = ConfigValues.getActivityUrl();
        logger.info("---------活动网址------------");
        logger.info(url);
        TreeMap<String,Object> map = new TreeMap<>();
        try {
            map.put("openid", URLEncoder.encode(openid,"utf-8"));
            map.put("fromid",URLEncoder.encode(fromid,"utf-8"));
            map.put("activityId",activityId);
            map.put("keyWay","2");
            map.put("timestamp",new Date().getTime()/1000);
            map.put("encryptKey","1234567a");
            map.put("checkCode", MD5Util.encrypt(MD5Util.dictSortTL(map)));
        }catch (Exception e){
            logger.info("--------加密失败----------");
        }
        map.remove("encryptKey");
        logger.info("---------加钥匙结果------------");
        logger.info(HttpsUtil.doGet(url,map,"utf-8",""));
    }

    private void executeImpl(String channel,String openid,String fromid,String type,String activityId){
        switch (channel){
            case ChannelConstant.NATIONAL_DAY_ACTIVITY :
                if(type == null){
                    sendWxMessage(openid);
                } else if ("a01".equals(type)) {
                    addChestCount(openid,fromid,activityId);
                }
                break;
            default: break;
        }
    }
}
